//
//  ReceiveDataListView.swift
//  swifttest1
//
//  Created by kologe on 2024/9/23.
//  description: 接受数据的scrollview的显示功能

import SwiftUI

class cellModel{
    var terminalName:String = ""
    var ip:String = ""
    var message:String = ""
    var btnTitle:[String] = []
}


//DataDelegate 是kztableview 需要的类型
struct ReceiveDataListView: View ,KzTableViewDelegate{
    
    @ObservedObject var dataDic = kzListener.conDic
    
    
    @State  var tableColumns:Array<KzTableColumn> = {
        let arr = ["TerminalName","Message","operation"] //排序
        let dic = ["TerminalName":"名称","Message":"信息","operation":"操作"]
        var tbArr:Array<KzTableColumn> = Array()
        arr.forEach { str in
            var tb = KzTableColumn()
            tb.identity = str
            tb.title = dic[str]!
            tb.ifPercent = true
            if str == "Message" {
                tb.percent = 0.5
            }else if str == "TerminalName" {
                tb.percent = 0.25
            }else if str == "operation" {
                tb.percent = 0.25
            }
            tbArr.append(tb)
        }
        return tbArr
    }()
    
    @State var dataSource:Array<Any> = Array()
//    @State var rowCounts = 0
    //
    @State var con2dataDic:Dictionary<Int,ConId> = Dictionary()
    
    var body: some View {
        GeometryReader{ geometry in
            VStack{
                Button(action: {
                    dataDic.state = false
                }, label: {
                    Image("return", label: Text("return")).frame(width: .infinity)
                    
                })
                .frame(width: 30)
                
                ScrollView(){
                    KzTableView<ReceiveDataListView>( delegate: self, tableColumns: $tableColumns, dataSource: $dataSource).frame(width: geometry.size.width)
                }.frame(width: geometry.size.width)
            }
        }.frame(width: 500,height: 300)
            .onAppear(){
                initDataSource()
            }
    }
    
    
    func initDataSource() {
        dataSource.removeAll()
        let tempArr = dataDic.keys()
        let sortArr:Array<ConId> = tempArr.sorted{ (id1,id2) ->Bool in
            if  let cm1 = dataDic[id1],let cm2 = dataDic[id2]{
                return cm1.timeStamp < cm2.timeStamp
            }else{
                return false
            }
        }
        var count = 0 //记录与connectionwrapper拥有的最后一个数据在datasource里面的位置
        for sortItem in sortArr{
            if let fileDic = dataDic[sortItem]?.fileDic{
                fileDic.forEach { (key: ConId, value: FileTransMessage) in
                    if 0 == value.ifTrans{
                        dataSource.append(value)
                        count += 1
                    }
                }
            }
            if let stringArr = dataDic[sortItem]?.wordsArr{
                stringArr.forEach { stringMessage in
                    dataSource.append(stringMessage)
                    count += 1
                }
            }
            con2dataDic[count] = sortItem
        }
    }
    
    func gridView(identify: String, data:Any) -> AnyView {
        
        if let sm = data as? StringMessage{
            return AnyView(Text(sm.getStringByIdentity(identify: identify)).multilineTextAlignment(.center))
        }
        else if  let ftm = data as? FileTransMessage{
            if(identify == "operation")
            {
                return operationBtn(data:ftm)
            }
            else if(identify == "Message")
            {
                return AnyView( ToolTipText(title: ftm.getStringByIdentity(identify: identify)) )
            }
            return AnyView( Text(ftm.getStringByIdentity(identify: identify)).multilineTextAlignment(.center) )
        }
        return AnyView(Text("default"))
        
    }
    func operationBtn(data:FileTransMessage)-> AnyView{
        if 1 == data.ifTrans{
            return AnyView(
            Text("--")
            )
        }else{
            return AnyView (
                HStack{
                    Button(
                        action: {
                            acceptFile(data:data)
                            //修改数据信息
                        }, label: {
                            Text("接受")
                        }
                    ).nomalStyle()
                    Button(
                        action: {
                            rejectFile(data:data)
                        }, label: {
                            Text("取消")
                        }
                    ).nomalStyle()
                }
            )
        }
    }
    
    
    
    func acceptFile(data:FileTransMessage){
        responseFile(data: data, state: 1)
        //判断是否有该data，决定是否使用该数据
        for item in fileDownloadArr.array{
            if item == data{
                return
            }
        }
        fileDownloadArr.add(obj: data)
    }
    func rejectFile(data:FileTransMessage){
        responseFile(data: data, state: 0)
    }
    
    func responseFile(data:FileTransMessage,state:UINT32){
        if 1 == data.ifTrans{
            return
        }
        data.ifTrans = state
        
        let connection = kzListener.conDic[data.conID]
        
        let fm = FileMessage()
        fm.state = 1
        fm.fileId = data.fileId
        if let jsonData = FileMessage.enCodeToJson(obj: fm){
            let pkgData = PackageHead.packageData(msgData: jsonData, type: FILE_MESSAGE_ANS)
            
            connection?.con.send(content: pkgData, completion:.contentProcessed({ error in
                if let error = error{
                    error_log("server send fileAns Data failed: \(error)")
                }else{
                    print("server send fileAns Data succcessfully")
                }
            }))
        }else{
            print("FileMessage.enCodeToJson failed")
        }
        
    }
    
    

    

    
}

//#Preview {
//    ReceiveDataListView()
//}
extension StringMessage{
    func getStringByIdentity(identify: String) -> String{
        if identify == "TerminalName" {
            return self.hostName
        }else if identify == "Message"{
            return self.message
        }
        return "default"
    }
}

extension FileTransMessage{
    func getStringByIdentity(identify: String) -> String{
        if identify == "TerminalName" {
            return kzListener.conDic[self.conID]?.hostName ?? "no name"
        }else if identify == "Message"{
            return self.fileName!
        }
        return "default"
    }
}


